//获取应用实例
const app = getApp()
var template = require('../../utils/tabBarTemplate/tabBarTemplate.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    wxToken:'',
    userInfo:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    var that = this;
    //tabbar菜单
    template.tabbar("tabBar", 3, this)//0表示第一个tabbar

    var _token = wx.getStorageSync("token");
    var _user = wx.getStorageSync("userInfoList");
    if (_token != undefined){
      that.setData({
        wxToken: _token,
        userInfo: _user
      })
    }
  },
  //获取用户信息
  bindGetUserInfo: function (e) {
    var that = this;
    var loginID = wx.getStorageSync("codeId");
    var _token = wx.getStorageSync("token");

    if (loginID == "" || _token == "") {
       //用户按了允许授权按钮
      if (e.detail.userInfo) {
        //存储本地
        // wx.setStorageSync('userInfo', e.detail.userInfo)
        //经纬度
        wx.getLocation({
          type: 'gcj02',
          success: (res) => {
            wx.setStorageSync('location', res)
          },
        })
        //登录
        wx.login({
          success: function (res) {
            console.info(res);
            wx.setStorageSync('codeId', res.code);
            app.globalData.code_key = res.code;
            if (res.code) {
              //获取openid
              wx.request({
                url: app.globalData.httpsPath + '/get-openid', // 接口地址
                method: "POST",
                data: {
                  code: wx.getStorageSync("codeId")
                },
                header: {
                  'content-type': 'application/json' // 默认值
                },
                success(res) {
                  // console.info(res)
                  if (res.data.status == true) {
                    var _key = res.data.openid;
                    var _session_key = res.data.session_key;
                    wx.setStorageSync('openid', _key);
                    //获取用户信息
                    wx.getUserInfo({
                      success: function (res) {
                        var _iv = res.iv;
                        var _encryptedData = res.encryptedData;
                        //3.请求自己的服务器，解密用户信息 获取unionId等加密信息
                        wx.request({
                          url: app.globalData.httpsPath + '/get-wx-user', // 接口地址
                          method: "POST",
                          data: {
                            session_key: _session_key,
                            iv: _iv,
                            encryptData: _encryptedData
                          },
                          header: {
                            'content-type': 'application/json' // 默认值
                          },
                          success(res) {
                            // console.info(res.data.data);
                            app.globalData.userInfoList = res.data.data;
                            wx.setStorageSync('userInfoList', res.data.data);
                            var userinfo = res.data.data;
                            setTimeout(function () {
                              var _location = wx.getStorageSync("location");
                              var _openid = wx.getStorageSync("openid");
                              if (_location == "") {
                                wx.getSetting({
                                  success: (res) => {
                                    if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {//非初始化进入该页面,且未授权
                                      wx.showModal({
                                        title: '是否授权当前位置',
                                        content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
                                        success: function (res) {
                                          if (res.cancel) {
                                            console.info("授权失败返回数据");
                                          } else if (res.confirm) {
                                            wx.openSetting({
                                              success: function (data) {
                                                if (data.authSetting["scope.userLocation"] == true) {
                                                  //获取经纬度
                                                  wx.getLocation({
                                                    type: 'gcj02',
                                                    success: (res) => {
                                                      wx.setStorageSync('location', res)
                                                    },
                                                  })
                                                  wx.showToast({
                                                    title: '授权成功',
                                                    icon: 'success',
                                                    duration: 3000
                                                  })

                                                } else {
                                                  wx.showToast({
                                                    title: '授权失败',
                                                    icon: 'success',
                                                    duration: 3000
                                                  })
                                                }
                                              }
                                            })
                                          }
                                        }
                                      });
                                    }
                                  }
                                })
                              } else {
                                wx.request({
                                  url: app.globalData.httpsPath + '/get-token', // 接口地址
                                  method: "POST",
                                  data: {
                                    mobile: '',
                                    name: '',
                                    nickname: userinfo.nickName,
                                    avatar: userinfo.avatarUrl,
                                    longitude: _location.longitude,
                                    latitude: _location.latitude,
                                    small_openid: _openid,
                                    unionid: ''
                                  },
                                  header: {
                                    'content-type': 'application/json' // 默认值
                                  },
                                  success(res) {
                                    // console.info(res.data.data.token)
                                    wx.setStorageSync('token', res.data.data.token);
                                    wx.setStorageSync('user_id', res.data.data.user_id);
                                    wx.showToast({
                                      title: '登录成功',
                                      icon: 'succes',
                                      duration: 3000,
                                      mask: true
                                    })
                                    setTimeout(function () {
                                      that.setData({
                                        wxToken: res.data.data.token,
                                        userInfo: userinfo
                                      })
                                    }, 2000)

                                  }
                                })
                              }
                            },1000)

                          }
                        })
                      },
                      fail: function () {
                        console.log('获取用户信息失败')
                      }
                    })

                  }
                }
              })
            } else {
              console.log("用户登录失败")
            }

          }
        });
      } else {//用户按了拒绝按钮
        wx.showModal({
          title: '警告',
          content: '您点击了拒绝授权，将无法点击职工相关内容，请授权之后再进入!!!',
          showCancel: false,
          confirmText: '返回授权',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击了“返回授权”')
            }
          }
        })
      }
    } 
  },
  // 跳转到订单列表
  orderJump:function(){
    wx.navigateTo({
      url: '/pages/orderList/orderList',
    })
  },

  getOrder:function(e) {
    var status = e.currentTarget.dataset.status;
    console.info(e);
    wx.navigateTo({
      url: '/pages/orderList/orderList?status='+status,
    })
  },

  //跳转到 地址 管理列表
  addressJump:function(){
    var _token = wx.getStorageSync("token");
    if (_token == '') {
      wx.showToast({
        title: '请先登录',
        icon: 'fail',
        duration: 2000,
        mask: true
      })
    } else {
      wx.navigateTo({
        url: '/pages/addressList/addressList?pagesType=lookOver',
      })
    }
    
  },
  //跳转到我的优惠券
  myCoupon:function(){
    wx.navigateTo({
      url: '/pages/couponList/couponList?pagesType=lookOver',
    })
  },
})